#include "mystdio.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

mFILE *mfopen(const char *filename, const char *mode)
{
    int fd = -1;
    if (strcmp(mode, "r") == 0)
    {
        fd = open(filename, O_RDONLY);
    }
    else if (strcmp(mode, "w") == 0)
    {
        fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    }
    else if (strcmp(mode, "a") == 0)
    {
        fd = open(filename, O_CREAT | O_WRONLY | O_APPEND, 0666);
    }
    if (fd < 0) return NULL;
    mFILE *mf = (mFILE*)malloc(sizeof(mFILE));
    if (mf == NULL)
    {
        close(fd);
    }

    mf->fileno = fd;
    mf->flag = FLUSH_LINE;
    mf->size = 0;

    return mf;
}

int mfwrite(const void *ptr, int num, mFILE *stream)
{
    //1. 拷贝到用户级缓冲区中
    memcpy(stream->outbuffer + stream->size, ptr, num);
    stream->size += num;

    //2. 判断是否为行缓冲
    if (stream->flag == FLUSH_LINE && stream->outbuffer[stream->size - 1] == '\n')
    {
        mfflush(stream);
    }

    return num;
}
void mfflush(mFILE *stream)
{
    //写到文件内核级缓冲区中
    if (stream->size > 0)
    {
        write(stream->fileno, stream->outbuffer, stream->size);
    }
    fsync(stream->fileno);
    stream->size = 0;
}
void mfclose(mFILE *stream)
{
    if (stream->size > 0)
    {
        mfflush(stream);
    }
    close(stream->fileno);
    free(stream);
}
